#ifndef TEMPLE_MOD_QUEUE_HANDLER_H_
#define TEMPLE_MOD_QUEUE_HANDLER_H_

#include "util/stdc.h"
namespace mod {

template<class T>
class QueueHandler
{
public:
    inline QueueHandler()
    {
        alive = false;
        threads = nullptr;
    }

    inline ~QueueHandler()
    {
        stop();
    }

    inline int start(std::function<void(T &&)> func, int thread_num = 1)
    {
        alive = true;
        threads.resize(thread_num);
        handler = func;

		for (auto thread : threads)
		{
			thread = new std::thread(entry, this);
		}

        return 0;
    }

    inline void stop()
    {
        if (alive)
        {
            alive = false;

			for (auto thread : threads)
			{
				thread->join();
				delete thread;
			}
        }
    }

	void deliver(const T &msg)
	{
		queue.push(msg);
	}

	void deliver(T &&msg)
	{
		queue.push(std::move(msg));
	}

private:
    bool alive;
    std::vector<std::thread *> threads;
	std::function<void(T &&)> handler;
	util::Queue<T> queue;

	void main_entry()
	{
        T msg;

        while (alive)
		{
			if (!queue.wait(msg, 100))
    			handler(std::move(msg));
		}
	}

    static void entry(QueueHandler *queue_handler)
    {
        queue_handler->main_entry();
    }
};

}
#endif //TEMPLE_MOD_QUEUE_HANDLER_H_
